﻿using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Microsoft.Phone.Reactive;
using RssReaderTemplate.Model;
using RssReaderTemplate.Repositories;

namespace RssReaderTemplate.ViewModels
{
    [DataContract]
    public class ListViewModel : NetworkRequiredViewModel, IObserver<RssItem>
    {
        IDisposable _subscription;

        public ListViewModel(RssRepository repository)
        {
            _subscription = repository.ObserveOnDispatcher().Subscribe(this);
        }

        protected ListViewModel()
        { }

        private ObservableCollection<RssItem> _feedItems = new ObservableCollection<RssItem>();

        [DataMember]
        public ObservableCollection<RssItem> FeedItems
        {
            get { return _feedItems; }
            set { _feedItems = value; }
        }

        private bool _error = false;
        [DataMember]
        public bool Error
        {
            get { return _error; }
            set {
                _error = value;
                OnPropertyChanged("Error");
            }
        }

        private int _selectedItemIndex = -1;
        [DataMember]
        public int SelectedItemIndex
        {
            get { return _selectedItemIndex; }
            set { _selectedItemIndex = value; }
        }


        public void OnCompleted()
        {
            _subscription.Dispose();
        }

        public void OnError(Exception exception)
        {
            Error = true;
        }

        public void OnNext(RssItem value)
        {
            _feedItems.Insert(_feedItems.Count, value);
        }
    }
}
